import { CorporateEntity, User, Role } from '../models';
import { getDefaultCategory } from './corporate_entity_categories';
import { createDefaultRolesForEntity } from './roles';

import Sequelize from 'sequelize';

export async function getDefaultCorporate(){
    const cate = await getDefaultCategory();
    const rlt =  await CorporateEntity.findOrCreate(
        {
            where: {isDefault: true}, 
            defaults: {
            createdAt: new Date(),
            updatedAt: new Date(),
            CorporateEntityCategoryId: cate.id,
            name: "????"
        }
    })

    const [entity, created] = rlt;

    if(created){
        await createDefaultRolesForEntity(entity.id);
    }

    return entity.get({
        plant: true,
    });
}

export async function getEnityOwner(entityId){
    const role = await Role.findOne({
        where: {CorporateEntityId: entityId, owner: true},
        include: [
            {
                model: User,
            }
        ]
    })
    return role.dataValues.Users
}